const positionTpl = require('../views/position.html');
const positionUpdateTpl = require('../views/positionUpdate.html');

// const template = require('art-template');
// const path = require('path');

const positionController = {
    async render({ res, router }) {
        //获取职位列表数据
        let positionList = await this.getList();
        // console.log(positionList);
        // 渲染页面
        let tpl = template.render(positionTpl, {
            data: positionList
        });
        res.render(tpl);
        this.updateItem({ res, router });
        this.removeItem({ res, router });
        // res.render(positionTpl); //注意 res的render渲染不能重复 否则会造成模板渲染的故障
        $('#goPositionAdd').click(() => {
            router.go('/position_add'); //路由跳转
        });
    },
    async getList() {
        let positionList = null;
        await $.ajax({
            type: "get",
            url: "/interface/position/find",
            dataType: "json",
            success: function(res) {
                positionList = res;
            }
        });
        return positionList;
    },
    removeItem({ res, router }) {
        let _this = this;
        $("tr[data-id] .zmh-remove-item").click(function() {
            let id = $(this).parents('tr').attr('data-id');
            let companyLogo = $(this).parents('tr').attr('data-img');
            $.ajax({
                url: '/interface/position/remove',
                data: {
                    id,
                    companyLogo
                },
                type: 'delete',
                success(result) {
                    _this.render({ res, router });
                    router.go('/position');
                    console.log('删除成功');
                }
            });
        });
    },
    updateItem({ res, router }) {
        let _this = this;
        $("tr[data-id] .zmh-update-item").click(function() {
            let value = JSON.parse($(this).parents('tr').attr('data-value'));
            // let tpl = template.render(positionUpdateTpl, {
            //     value
            // });
            // res.render(tpl);
            // $.ajax({
            //     url: '/interface/position/update',
            //     data: value,
            //     type: 'post',
            //     success(result) {
            //         _this.render({ res, router });
            //         router.go('/position');
            //         console.log('修改成功');
            //     }
            // });
            router.go(`/position_update`, value);
        });
    }
};

module.exports = positionController;